package protocol

import (
	"encoding/binary"
	"errors"
	"math/rand"
	"sync/atomic"
	"time"
)

//cloudSvr
//client
//edgeClient

//1 hb
//2 wakeup
//3 begin
//4 probe
const KCP = 0
const HB = 1
const WAKEUP = 2
const BEGIN = 3
const PROBE = 4
const GETLIST = 5
const WAKEUP_RES = 6
const BEGIN_KCP = 7

//Header 协议头
type Header struct {
	Ptype byte
	Seq   uint32
	Body  []byte
}

var seq uint32

func init() {
	rand.Seed(time.Now().UnixNano())
	seq = rand.Uint32()
}

//GetHeader 解析协议获取协议头
func GetHeader(body []byte, blen int) (*Header, error) {
	alen := len(body)
	if alen < 5 && blen <= alen {
		return nil, errors.New("buffer is too short")
	}
	pHeader := &Header{
		Ptype: body[0],
		Seq:   binary.BigEndian.Uint32(body[1:5]),
		Body:  body[5:blen],
	}
	return pHeader, nil
}

func (pHeader *Header) MakeSeq() {
	atomic.AddUint32(&seq, 5)
	pHeader.Seq = seq
}

func (pHeader *Header) ToBuffer(buffer []byte) (int, error) {
	bufflen := len(buffer)
	bodylen := len(pHeader.Body)
	sendlen := 5 + bodylen
	if bufflen >= sendlen {
		buffer[0] = pHeader.Ptype
		binary.BigEndian.PutUint32(buffer[1:], pHeader.Seq)
		copy(buffer[5:], pHeader.Body)
		return sendlen, nil
	} else {
		return 0, errors.New("buffer is too small")
	}

}
